<template>
  <div>
    <el-dialog
      :visible.sync="dialogVisible"
      :close-on-click-modal="false"
      :append-to-body="true"
      title="选择商品"
      center
      fullscreen
      @close="close"
    >
      <div v-loading="loading">
        <!-- filter start -->
        <div class="filter-container">
          <el-form ref="filterForm" :model="filterForm" inline label-width="100px" size="small">

            <el-form-item prop="title" label="商品名称：">
              <el-input v-model="filterForm.title" />
            </el-form-item>
            <el-form-item prop="goodsNo" label="商品编码：">
              <el-input v-model="filterForm.goodsNo" />
            </el-form-item>

            <el-form-item prop="goodsType" label="商品类型：">
              <el-select v-model="filterForm.goodsType" placeholder="请选择">
                <el-option label="全部" value="all" />
                <template v-for="(item,key) in goodsTypeOptions">
                  <el-option v-if="goodsTypes.length===0||goodsTypes.includes(Number(key))" :key="key" :label="item" :value="key" />
                </template>
              </el-select>
            </el-form-item>
            <el-form-item prop="categoryId" label="商品类目：">
              <el-cascader
                v-model="filterForm.categoryId"
                :options="categoryTreeOptions"
                :show-all-levels="false"
                :props="{ expandTrigger: 'hover',checkStrictly: true,label:'title' ,value:'id'}"
                class="w-300"
              />
            </el-form-item>

            <el-form-item v-if="manageMode === 'multiple'" prop="skuStatus" label="商品状态：">
              <el-select v-model="filterForm.skuStatus" placeholder="请选择">
                <el-option label="全部" value="all" />
                <el-option v-for="(item, key) in skuStatusOptions" :key="key" :label="item" :value="key" />
              </el-select>
            </el-form-item>
            <el-form-item v-else prop="status" label="商品状态：">
              <el-select v-model="filterForm.status" placeholder="请选择">
                <el-option label="全部" value="all" />
                <el-option v-for="(item, key) in skuStatusOptions" :key="key" :label="item" :value="key" />
              </el-select>
            </el-form-item>
            <div>
              <el-form-item label=" ">
                <el-button type="primary" round @click="search">查 询</el-button>
                <el-button round @click="reset">重 置</el-button>
              </el-form-item>
            </div>
          </el-form>
        </div>
        <!-- filter end -->

        <!-- table start -->
        <div class="table-container">
          <el-tag v-if="maxGoodsNum||maxSkuNum" effect="dark" style="margin-bottom: 10px">
            最多选择{{ maxGoodsNum ? `【 ${maxGoodsNum} 】种商品` : '' }} {{ maxSkuNum ? `【${maxSkuNum}】个SKU` : '' }}
          </el-tag>
          <el-table :data="skuList" :span-method="arraySpanMethod" :cell-style="formatCellStyle" border stripe style="width: 100%" size="small" empty-text="暂无数据">
            <el-table-column prop="goods.title" label="商品">
              <template slot-scope="scope">
                <div class="goods-info-box flexRSC">
                  <div class="cover-img">
                    <img v-if="scope.row.goods.coverImg" :src="fileBaseUrl + scope.row.goods.coverImg" alt srcset>
                  </div>
                  <div>
                    <div class="goods-title app-line-two">
                      {{ scope.row.goods.title }}
                    </div>
                    <div class="goods-detail app-line-two">
                      <span
                        v-if="scope.row.goods.categoryId === 0 ||scope.row.goods.category.length === 0"
                      >无归属类目</span>
                      <span v-else>
                        <span v-for="(attr, attrIndex) in scope.row.goods.category" :key="attrIndex">
                          {{ attr }}
                          <span v-if="attrIndex + 1 !== scope.row.goods.category.length">/</span>
                        </span>
                      </span>
                    </div>
                    <div class="goods-detail app-line-two">
                      {{ goodsTypeOptions[scope.row.goods.goodsType] }}
                    </div>
                  </div>
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="skuList" label="属性">
              <template slot-scope="scope">
                <span v-if="scope.row.skuInfo.specAttrNameList.length === 0">-</span>
                <span v-else>
                  <span v-for="(attr, attrIndex) in scope.row.skuInfo.specAttrNameList" :key="attrIndex">
                    {{ attr }}
                    <span v-if="attrIndex + 1 !== scope.row.skuInfo.specAttrNameList.length">/</span>
                  </span>
                </span>
              </template>
            </el-table-column>
            <el-table-column prop="skuList.skuInfo.originPrice" label="市场价/元" width="110">
              <template slot-scope="scope">{{
                scope.row.skuInfo.originPrice / 100
              }}
              </template>
            </el-table-column>
            <el-table-column prop="skuList.skuInfo.price" label="参考售价/元" width="110">
              <template slot-scope="scope">{{
                scope.row.skuInfo.price / 100
              }}
              </template>
            </el-table-column>

            <!-- 多店铺  -->
            <!--<div v-if="filterForm.manageMode === 'multiple'">-->
            <!--  <el-table-column prop="skuList.storeCount" label="出价店铺" width="110">-->
            <!--    <template slot-scope="scope">{{ scope.row.storeCount }} 家门店</template>-->
            <!--  </el-table-column>-->
            <!--  <el-table-column prop="skuList.skuInfo.status" label="状态" width="110">-->
            <!--    <template slot-scope="scope">-->
            <!--      <div-->
            <!--        :class="-->
            <!--          scope.row.skuInfo.status-->
            <!--            ? 'app-text-color-primary'-->
            <!--            : 'app-text-color-danger'-->
            <!--        ">-->
            <!--        {{ skuStatusOptions[scope.row.skuInfo.status] }}-->
            <!--      </div>-->
            <!--    </template>-->
            <!--  </el-table-column>-->
            <!--</div>-->
            <!-- 单店铺  -->
            <!--<div v-if="filterForm.manageMode === 'single'">-->
            <!--  <el-table-column prop="skuList.skuInfo.price" label="店铺售价/元" width="110">-->
            <!--    <template slot-scope="scope">{{-->
            <!--      scope.row.storePrice == -1-->
            <!--        ? scope.row.skuInfo.originPrice / 100-->
            <!--        : scope.row.storePrice / 100-->
            <!--    }}-->
            <!--    </template>-->
            <!--  </el-table-column>-->

            <!--  <el-table-column prop="storeStatus" label="店铺在售" width="110">-->
            <!--    <template slot-scope="scope">-->
            <!--      <el-switch v-model="scope.row.storeStatus" :active-value="1" :nactive-value="0" @change="(val) => changeSingleState(val, scope.row)"/>-->
            <!--    </template>-->
            <!--  </el-table-column>-->
            <!--  <el-table-column prop="skuList.skuInfo.price" label="库存" width="110">-->
            <!--    <template slot-scope="scope">{{-->
            <!--      scope.row.storeInventory-->
            <!--    }}-->
            <!--    </template>-->
            <!--  </el-table-column>-->
            <!--</div>-->

            <el-table-column label="选择" width="120">
              <template slot-scope="scope">
                <el-checkbox
                  v-model="checkedSkuIds"
                  :disabled="originalCheckedSkuIds.includes(scope.row.skuInfo.skuId)||
                    maxSkuNum&&checkedList.length>=maxSkuNum&&!checkedListSkuIds.includes(scope.row.skuInfo.skuId)||
                    maxGoodsNum&&checkedListGoodsIds.length>=maxGoodsNum&&!checkedListGoodsIds.includes(scope.row.goods.goodsId)
                  "
                  :label="scope.row.skuInfo.skuId"
                  @change="(val)=>checkboxChange(val,scope.row)"
                >
                  {{ checkedSkuIds.includes(scope.row.skuInfo.skuId) ? '已选' : '选择' }}
                </el-checkbox>
                <!--<span>{{ scope.row.goods.goodsId }}</span>-->
              </template>
            </el-table-column>
          </el-table>
          <!-- table end -->
          <!-- 分页 -->
          <pagination-direction v-if="paginationConfig.total !== 0" :config="paginationConfig" @sizeschange="fetchData" @pagechange="fetchData" />
        </div>

      </div>
      <div slot="footer" style="position:sticky" class="dialog-footer">
        <el-button :disabled="loading||checkedList.length===0" size="small" round type="primary" @click="submit">
          确定<span>（ 已选 {{ checkedList.length }}  ）</span></el-button>
        <el-button :disabled="loading" size="small" round @click="hide">取消</el-button>
      </div>

    </el-dialog>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import { productSkuList, productSkuListByShop } from '@/views/wxaMallModule/api/sku'
import { categoryTree } from '@/views/wxaMallModule/api/category'

export default {
  props: {
    manageMode: {
      type: String,
      default: 'multiple'
    },
    storeId: {
      type: Number,
      default: null
    },
    goodsTypes: {
      type: Array,
      default: () => {
        return []
      }
    },
    maxGoodsNum: {
      type: Number,
      default: null
    },
    maxSkuNum: {
      type: Number,
      default: null
    }
  },
  data() {
    return {
      // 分页配置
      paginationConfig: {
        direction: 'center', // 分页位置
        layout: 'total, sizes, prev, pager, next, jumper', // 分页类型
        pageSizes: [10, 20], // 分页pages
        total: 0,
        page: 1, // 页数-默认1
        pageSize: 10 // 每页条数-默认10
      },
      skuStatusOptions: {
        0: '已下架',
        1: '已上架'
      },
      // 配置
      resolve: null,
      reject: null,
      goodsTypeOptions: {
        100: '实物商品',
        101: '配件商品',
        200: '卡/券包'
      },
      goodsDeliveryOptions: {
        // 1: "canExpress",
        2: '同城配送',
        3: '到店自提'
        // 3: "券包",
        // 300: "同城配送",
      },
      statusOptions: {
        0: '已下架',
        1: '已上架'
      },
      categoryTreeOptions: [],
      // 状态
      dialogVisible: null,
      loading: false,
      // 数据
      filterForm: {
        goodsType: 'all',
        barCode: '',
        brandId: '',
        categoryId: [0],
        goodsNo: '',
        title: '',
        storeId: null,
        skuStatus: 'all',
        status: 'all'
      },
      originalCheckedSkuIds: [],
      originalCheckedGoodsIds: [],
      checkedSkuIds: [],
      checkedGoodsIds: [],
      checkedList: [],
      checkedListSkuIds: [],
      checkedListGoodsIds: [],
      skuList: []
    }
  },
  computed: {
    ...mapGetters(['fileBaseUrl'])
  },
  watch: {},
  created() {
  },
  mounted() {
  },

  methods: {
    /**
     * 弹框相关
     */
    open({ checkedSkuIds = [], checkedGoodsIds = [] }) {
      this.originalCheckedSkuIds = checkedSkuIds
      this.originalCheckedGoodsIds = checkedGoodsIds
      this.checkedSkuIds = checkedSkuIds
      this.checkedListGoodsIds = checkedGoodsIds
      this.getCategoryOptions()
      this.fetchData(1)
      this.show()
      return new Promise((resolve, reject) => {
        this.resolve = resolve
        this.reject = reject
      })
    },

    show() {
      this.dialogVisible = true
    },

    close() {
      this.loading = false
      Object.assign(this.$data, this.$options.data())
      this.originalCheckedSkuIds = []
      this.checkedSkuIds = []
      this.checkedList = []
      this.checkedListGoodsIds = []
      this.checkedListSkuIds = []
      this.list = []
    },

    hide() {
      this.resolve = null
      this.reject = null
      this.dialogVisible = false
    },

    /**
     * 数据组
     */
    // 获取列表
    fetchData(
      pageNum = this.paginationConfig.page,
      pageSize = this.paginationConfig.pageSize
    ) {
      // 加入page
      this.filterForm.pageNum = pageNum
      this.filterForm.pageSize = pageSize
      const params = Object.assign({}, this.filterForm)
      if (
        params.categoryId.length === 0 ||
        (params.categoryId.length === 1 && params.categoryId[0] === 0)
      ) {
        params.categoryId = ''
      } else {
        params.categoryId = params.categoryId[params.categoryId.length - 1]
      }
      if (params.goodsType === 'all' && this.goodsTypes.length) {
        params.goodsTypes = this.goodsTypes
      }
      // 清除多余字段
      for (const key in params) {
        if (params[key] === '' || params[key] === 'all') {
          delete params[key]
        }
      }
      this.loading = true
      if (this.manageMode === 'multiple') {
        delete params['storeId']
        delete params['status']
        productSkuList(params)
          .then((res) => {
            this.formatSkuList(res)
          })
          .finally(() => {
            this.loading = false
          })
      } else {
        delete params.skuStatus
        params.storeId = this.storeId
        productSkuListByShop(params)
          .then((res) => {
            this.formatSkuList(res)
          })
          .finally(() => {
            this.loading = false
          })
      }
    },

    // 格式化列表
    formatSkuList(res) {
      const skuList = []
      const skuRowSpan = {}
      res.data.list.forEach((item) => {
        skuRowSpan[item.goods.goodsId] = [0, 0]
        item.skuList.forEach((skuItem, skuIndex) => {
          if (skuIndex === 0) {
            skuRowSpan[item.goods.goodsId][0] = skuList.length
            skuRowSpan[item.goods.goodsId][1] = item.skuList.length
          }
          skuItem.goods = item.goods
          skuList.push(skuItem)
        })
      })
      this.skuRowSpan = skuRowSpan
      this.skuList = skuList
      this.list = res.data.list
      this.paginationConfig.total = res.data.total
      this.paginationConfig.page = res.data.pageNum
    },

    // 分页sizes改变
    sizesChange() {
      this.fetchData()
    },

    // 分页page改变
    pageChange() {
      this.fetchData()
    },

    // 获取类目tree
    getCategoryOptions() {
      return new Promise((resolve, reject) => {
        categoryTree()
          .then((res) => {
            this.categoryTreeOptions = [
              {
                categoryNo: '',
                children: undefined,
                id: 0,
                parentId: 0,
                ranking: 0,
                title: '全部'
              }
            ].concat(this.formatTreeData(res.data))
          })
      })
    },

    // children设置空
    formatTreeData(data) {
      for (let i = 0; i < data.length; i++) {
        if (data[i].children.length < 1) {
          data[i].children = undefined
        } else {
          this.formatTreeData(data[i].children)
        }
      }
      return data
    },

    /**
     * 按钮组
     */
    // 查询
    search() {
      this.fetchData(1)
    },

    // 重置
    reset() {
      this.$refs.filterForm.resetFields()
    },

    // 保存
    submit() {
      if (this.checkedList.length) this.resolve && this.resolve(JSON.parse(JSON.stringify(this.checkedList)))
      this.hide()
    },

    /*
    * 状态组
    * */
    // 多选
    checkboxChange(val, row) {
      console.log(9999, row, this.checkedSkuIds)
      if (val) {
        this.checkedList.push(row)
      } else {
        this.checkedList.splice(this.checkedList.findIndex(item => item.skuInfo.skuId === row.skuInfo.skuId), 1)
      }
      const checkedListGoodsIds = []
      const checkedListSkuIds = []
      this.checkedList.map(v => {
        checkedListGoodsIds.push(v.goods.goodsId)
        checkedListSkuIds.push(v.skuInfo.skuId)
      })
      this.checkedListGoodsIds = [...new Set(checkedListGoodsIds)]
      this.checkedListSkuIds = [...new Set(checkedListSkuIds)]
      console.log(this.checkedListGoodsIds)
    },
    /**
     * 方法组
     */
    // 合并单元格
    arraySpanMethod({ row, column, rowIndex, columnIndex }) {
      if (columnIndex === 0) {
        const spanArr = this.skuRowSpan[row.goods.goodsId]
        if (rowIndex === spanArr[0]) {
          return [spanArr[1], 1]
        } else {
          return [0, 0]
        }
      }
    },

    // 增长率样式
    formatCellStyle({ row, column, rowIndex, columnIndex }) {
      switch (columnIndex) {
        case 0:
          return {
            'vertical-align': 'top'
          }
      }
    }
  }
}
</script>
<style rel="stylesheet/scss" lang="scss" scoped>
.el-dropdown-link {
  margin-right: 10px;
  font-size: 12px;
}

.el-select,
.el-input,
.el-cascader {
  width: 250px;
}

/* 商品内容 */
.goods-info-box {
  .cover-img {
    margin-right: 10px;
    flex: 0 0 50px;
    height: 50px;
    border: 1px solid #e7e7e7;
  }

  .goods-title {
    font-size: 14px;
    font-weight: bold;
    color: #000;
  }

  .goods-detail {
    font-size: 12px;
  }
}
</style>
